package com.bradz.mymovies;

import java.net.HttpCookie;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpVersion;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

public class ClassClientHolder {
	private DefaultHttpClient client;
	private Object mLock = new Object();
	private CookieStore mCookie = null;
	private ClassAndroidLogger logger = new ClassAndroidLogger("ClassClientHolder");
	
	ClassClientHolder(){
		client = getHttpClient();
		logger.info("Initialized");
	}
	
	public DefaultHttpClient get_client(){
		return client;
	}
	
	public CookieStore get_cookies(){
		return client.getCookieStore();
	}
	
	public void set_cookiestore(CookieStore cookie_store){
		client.setCookieStore(cookie_store);
	}
	
	public DefaultHttpClient getHttpClient() {
		HttpParams params = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(params, 10000);
		HttpConnectionParams.setSoTimeout(params, 10000);
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        final DefaultHttpClient httpClient = new DefaultHttpClient(params);
        //HttpClientBuilder.create().build();
        //Can't have two clients storing cookies at the same time
        synchronized (mLock) {
            if (mCookie == null && httpClient.getCookieStore().getCookies().size()>0) {
            	logger.info("Creating new cookies");
                mCookie = httpClient.getCookieStore();
            } else if (mCookie == null && httpClient.getCookieStore().getCookies().size()<=0){
            	CookieStore cookieStore = new BasicCookieStore();
            	httpClient.setCookieStore(cookieStore); 
            	mCookie = httpClient.getCookieStore();
            }else {
            	logger.info("Passing cookies");
                httpClient.setCookieStore(mCookie);
            }
        }
        logger.info("Dispatching client");
        return httpClient;
	}
	
	public void print_cookie_names(){
		logger.info("Printing Cookie Info");
		for(Cookie cook : client.getCookieStore().getCookies()){
			logger.info(cook.getName() + ":" + cook.getValue());
		}
	}
	public void clone_cookies(CookieStore new_cookie_store){
		for(Cookie cook : client.getCookieStore().getCookies()){
			new_cookie_store.addCookie(cook);
		}
	}
}
